import { Component, OnInit, Input } from '@angular/core';

import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';

import { ModalController, AlertController, LoadingController, Platform } from "@ionic/angular";

import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { EventService } from 'src/app/shared/service/event.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';

declare var device;
declare var cordova;
@Component({
  selector: 'app-custom-popover',
  templateUrl: './custom-popover.component.html',
  styleUrls: ['./custom-popover.component.scss']
})
export class CustomPopoverComponent implements OnInit {
  openRemarks = false;
  @Input() tagData: any;
  @Input() type: string;
  appTypeCustom: any;
  constructor(
    private platform: Platform,
    public modalController: ModalController,
    private iab: InAppBrowser,
    private file: File,
    private fileOpener: FileOpener,
    private eventService: EventService,
    private transfer: FileTransfer,
    private loadingCtrl: LoadingController,
    private appGlobalService: AppGlobalService
  ) { }

  ngOnInit() {
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
  }

  update() {
    if (this.tagData.platform === 'ios') {
      const url = 'https://itunes.apple.com/app/id' + this.tagData.appId;
      this.iab.create(url, '_system');
      this.modalController.dismiss({ dismissed: true });
    } else {
      this.downloadApp(this.tagData.apkUrl);
    }
  }

  




  /**
   * https://github.com/guyromb/cordova-open-native-settings
   * ios locations
   *
  */

  openPermission() {
    if (cordova && cordova.plugins.settings) {
      console.log('openNativeSettingsTest is active');
      cordova.plugins.settings.open(this.tagData.settingType, () => {
        console.log('opened settings');
      },
        () => {
          console.log('failed to open settings');
        }
      );
    } else {
      console.log('openNativeSettingsTest is not active!');
    }
    this.modalController.dismiss({ dismissed: true });
  }
  close() {
    this.modalController.dismiss({ dismissed: true });
  }
  async downloadApp(url) {
    let timer;
    let num = 0;
    const loading = await this.loadingCtrl.create({
      message: '',
      backdropDismiss: false
    });
    loading.present();
    const targetUrl = url;
    const fileTransfer: FileTransferObject = this.transfer.create();
    console.log(this.file.dataDirectory);
    fileTransfer.download(targetUrl, this.file.dataDirectory + 'app.apk').then((entry) => {
      if (timer) { clearInterval(timer); loading.dismiss(); }
      this.fileOpener.open(entry.toURL(),
        'application/vnd.android.package-archive')
        .then(() => {
          console.log('msg-----> File is opened');
        })
        .catch(e => {
          console.log('msg-----> Error openening file', e);
        });
    }, (error) => {
      console.log('msg-----> download Error ', error);
    });
    fileTransfer.onProgress((event) => {
      num = Math.ceil(event.loaded / event.total * 100);
      timer = setInterval(() => {
        loading.message = "下载进度：" + Math.floor(num) + "%";
      });
      if (num >= 99) {
        clearInterval(timer);
      }
    });
  }

  agree() {
    localStorage.setItem('isFirstInstall', 'true');
    localStorage.setItem('privacyStatement', 'true');
    let deviceName: any;
    let deviceUUID: any;
    // 安卓需要 同意则初始化极光推送
    if (this.platform.is('android') && localStorage.getItem('client') !== 'BROWSER') {
      try {
        if (device) {
          deviceName = device.model;
        }
      } catch (error) {
        deviceName = 'unknow';
        deviceUUID = 'unknow';
      }

    }
    // 登录识别用
    localStorage.setItem('device', deviceName);
    // localStorage.setItem('androidAskForLocation','true');
    this.modalController.dismiss({ dismissed: true });
  }

  

  disAgree() {
    this.modalController.dismiss({ dismissed: true, deviceInfo: true });
  }

  agreeDevice(name, imei) {


  }

  disAgreeDevice() {
    this.modalController.dismiss({ dismissed: true });
  }

  gotoPrivacyPage() {
    this.alertPrivacyPolicy();
  }

  async alertPrivacyPolicy() {
    this.eventService.eventEmit.emit("openPage",
      // tslint:disable-next-line:no-string-literal
      JSON.stringify({ type: 'privacy', urlLinkTitle: "隐私权限", target: window['appGlobalService'].privatePolicyLink, params: {} }));
  }

  gotoJGPrivacy(url) {
    window.open(url, '_blank');
  }

  needRefreshTab() {
    setTimeout(() => {
      const tab = localStorage.getItem('tab');
      if (tab && tab.indexOf("tab") > -1) {
        const tabIndex = tab.substring(tab.length - 1);
        console.log("needRefreshTab" + tabIndex);
        localStorage.setItem('needRefreshTab' + tabIndex, 'true');
        this.eventService.eventEmit.emit(tab, '1');
        console.log('submit eventEmit--->' + tab);
      }
    }, 1000);
  }


  getInterger(value) {
    // tslint:disable-next-line:radix
    return parseInt(value);
  }
}
